package cn.huanba.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 */
@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * redis 存入
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * redis 存入,带有时效
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value,int time){
        try {
            redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * redis 取值
     * @param key
     * @return
     */
    public String get(String key){
        String value=null;
        try {
            value=redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

}
